package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class TestServiceImpl implements TestService {

    private final Lock lock =new ReentrantLock();
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void lock() {  //不见不散  只要拿不到lock 就会一直拿  直到能拿到lock为止
        //分布式锁  lock已经存在表示已上锁  lock不存在表示未上锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "1212");
        if (lock){
            //lock : true 表示未上锁
           Integer num = (Integer) redisTemplate.opsForValue().get("num");
           num++;
           redisTemplate.opsForValue().set("num",num);
           redisTemplate.delete("lock");
        }else{
            //lock : false 表示已上锁
            lock();
        }
    }


    /*//本地锁
    @Override
    public void lock() {
        lock.lock();
        try {
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            num++;
            redisTemplate.opsForValue().set("num",num);
        } finally {
            lock.unlock();
        }

    }*/
}
